package com.scan.bus.permission;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.PermissionChecker;


import com.scan.bus.R;
import com.yanzhenjie.permission.AndPermission;

import java.io.Serializable;
import java.util.HashMap;


public class PermissionsUtil {

    public static final String TAG = "PermissionGrantor";
    private static HashMap<String, PermissionListener> listenerMap = new HashMap();

    /**
     * 申请授权，当用户拒绝时，会显示默认一个默认的Dialog提示用户
     * @param context
     * @param listener
     * @param permission 要申请的权限
     */
    public static void requestPermission(Context context, PermissionListener listener, String... permission) {
        requestPermission(context, listener, permission, true, null);
    }

    /**
     *  申请授权，当用户拒绝时，可以设置是否显示Dialog提示用户，也可以设置提示用户的文本内容
     * @param context
     * @param listener
     * @param permission 需要申请授权的权限
     * @param showTip 当用户拒绝授权时，是否显示提示
     * @param tip 当用户拒绝时要显示Dialog设置
     */
    @SuppressLint("WrongConstant")
    public static void requestPermission(@NonNull Context context, @NonNull PermissionListener listener
            , @NonNull String[] permission, boolean showTip, @Nullable TipInfo tip) {
        
        if (listener == null) {
            Log.e(TAG, "listener is null");
            return;
        }
//        if (PermissionsUtil.hasPermission(context, permission)) {
//            listener.permissionGranted(permission);
//        } else {
//            if (Build.VERSION.SDK_INT < 23) {
//                listener.permissionDenied(permission);
//            } else {
//                String key = String.valueOf(System.currentTimeMillis());
//                listenerMap.put(key, listener);
//                Intent intent = new Intent(context, PermissionActivity.class);
//                intent.putExtra("permission", permission);
//                intent.putExtra("key", key);
//                intent.putExtra("showTip", showTip);
//                intent.putExtra("tip", tip);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//
//                context.startActivity(intent);
//            }
//        }
        AndPermission.with(context)
                .runtime()
                .permission(permission)
                .onGranted(permissions -> {
                    listener.permissionGranted(permission);
                })
                .onDenied(permissions -> {
                    listener.permissionDenied(permission);
                    PermissionActivity.showMissingPermissionDialog(context,tip);
                })
                .start();

    }

    //首页专属，不能删除
    @SuppressLint("WrongConstant")
    public static void FirstPageRequestPermission(@NonNull Context context, @NonNull PermissionListener listener
            , @NonNull String[] permission, boolean showTip, @Nullable TipInfo tip) {

        if (listener == null) {
            Log.e(TAG, "listener is null");
            return;
        }
        AndPermission.with(context)
                .runtime()
                .permission(permission)
                .onGranted(permissions -> {
                    listener.permissionGranted(permission);
                })
                .onDenied(permissions -> {
                    showMissingPermissionDialog(context,tip,listener,permission);
                })
                .start();

    }

    // 显示缺失权限提示
    public static void showMissingPermissionDialog(Context context, TipInfo tipInfo1, @NonNull PermissionListener listener
            , @NonNull String[] permission) {
        final PermissionDialog promptDialog = new PermissionDialog((Activity) context);
//        promptDialog.setTvSureColor(R.color.new_text);
//        promptDialog.setTvSureBg(R.drawable.bg_dialog_bottomr);
        String content="请先打开相关权限之后再操作..";
        String cancel=context.getResources().getString(R.string.permission101_quxiao);

        if (tipInfo1!=null){
            if (!TextUtils.isEmpty(tipInfo1.content)){
                switch (tipInfo1.content){
                    case "1":
                        content=context.getResources().getString(R.string.permission1_neicunka);
                        break;
                    case "2":
                        content=context.getResources().getString(R.string.permission2_maike);
                        break;
                    case "3":
                        content=context.getResources().getString(R.string.permission3_dianhua);
                        break;
                    case "4":
                        content=context.getResources().getString(R.string.permission4_tongxunlu);
                        break;
                    case "5":
                        content=context.getResources().getString(R.string.permission5_dingwei);
                        break;
                    case "6":
                        content=context.getResources().getString(R.string.permission6_xiangji);
                        break;
                    case "7":
                        content=context.getResources().getString(R.string.permission7_bufeng);
                        break;
                    case "8":
                        content=context.getResources().getString(R.string.permission8_calendar);
                        break;
                    case "9":
                        content=context.getResources().getString(R.string.permission9_phonestate);
                        break;
                }
            }
            if ("8".equals(tipInfo1.cancel)){
                cancel=context.getResources().getString(R.string.permission100_tuichu);
            }else if ("102".equals(tipInfo1.cancel)){
                cancel=context.getResources().getString(R.string.permission102_yihouzaishuo);
            }else{
                cancel=context.getResources().getString(R.string.permission101_quxiao);
            }
        }
        promptDialog.setSureAndCancleListener("请开启权限",content,"", "去启动",
                (v) -> {
                    promptDialog.dismiss();
                    PermissionsUtil.gotoSetting(context);
                }, cancel, (v) -> {
                    listener.permissionDenied(permission);
                    promptDialog.dismiss();
                }).show();

    }

    /**
     * 判断权限是否授权
     * @param context
     * @param permissions
     * @return
     */
    //不能完全依靠此方法，因为部分手机不兼容，权限不开也会返回true，如手机OPPOR9st ,ColorOs版本V3.0,android版本6.0.1
    public static boolean hasPermission(@NonNull Context context, @NonNull String... permissions) {

        if (permissions.length == 0) {
            return false;
        }

        for (String per : permissions ) {
            int result = PermissionChecker.checkSelfPermission(context, per);
            if ( result != PermissionChecker.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }

    /**
     * 判断一组授权结果是否为授权通过
     * @param grantResult
     * @return
     */
    public static boolean isGranted(@NonNull int... grantResult) {

        if (grantResult.length == 0) {
            return false;
        }

        for (int result : grantResult) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 跳转到当前应用对应的设置页面
     * @param context
     */
    public static void gotoSetting(@NonNull Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    /**
     *
     * @param key
     * @return
     */
    static PermissionListener fetchListener(String key) {
        return listenerMap.remove(key);
    }


    public static class TipInfo implements Serializable {

        private static final long serialVersionUID = 1L;

        String title;
        String content;
        String cancel;  //取消按钮文本
        String ensure;  //确定按钮文本

        public TipInfo (@Nullable String title, @Nullable String content, @Nullable String cancel, @Nullable String ensure) {
            this.title = title;
            this.content = content;
            this.cancel = cancel;
            this.ensure = ensure;
        }
    }
}
